//
//  EBChapter.m
//  UMDReader
//
//  Created by 张 霄鹤 on 10-2-1.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import <zlib.h>
#import "EBChapter.h"


@implementation EBChapter

@synthesize title;

- (id)init{
	if(self = [super init]){
		title = @"无标题";
		content = [[NSMutableData alloc] init];
	}
	return self;
}

- (void)load:(BEDataInputStream *)din{
	bZiped = ([din read] == 1);
	NSInteger rlen = 0;
	NSInteger len;
	NSInteger bf = 0;
	char *buf;
	
	totalLength = [din readInt];
	
	do{
		len = [din readInt];
		if(len > 0){
			buf = [din getCurrentBytesRefwithLength:len retLength:&rlen];
			if(rlen > 0){
				[content appendBytes:buf length:rlen];
			}
		}
		bf = [din read];
	}while(bf == 1);
}

- (NSString *)getContent{
	NSString *ret = nil;
	if(!textContent){
		NSInteger len = [content length];
		if(len>0){
			if(bZiped){
				if(totalLength > -1){
					char dest[totalLength];
					char *buf = (char *)[content bytes];
					uLongf dlen = totalLength;
					uLong blen = len;
					int zret = uncompress((Bytef *)dest, &dlen, (Bytef *)buf, blen);
					if(zret == Z_OK){
						textContent = [[NSString alloc] initWithBytes:dest length:(NSInteger)dlen encoding:NSUTF8StringEncoding];
						buf = nil;
						ret = textContent;
						[content release];
					}else{
						buf = nil;
					}
				}else{
					// TODO 处理那些没有长度的
				}								
			}else{
				textContent = [[NSString alloc] initWithData:content encoding:NSUTF8StringEncoding];
				ret = textContent;
				[content release];
			}
		}
	}else{
		ret = textContent;
	}
	return ret;
}

- (void)dealloc{
	[title release];
	if(content){
		[content release];
	}
	if(textContent){
		[textContent release];
	}
	[super dealloc];
}

@end
